<template>
  <div class="one-index-content">
    <div class="setting-content">
      <p class="data-statistic-title">设置指标</p>
      <p class="detail-tile">通过选择某个阶段的某个CRF表中的某道题目作为统计指标</p>
    </div>
    <avue-form
      :option="option"
      v-model="form"
      style="margin-top: 20px"
      @submit="handleSubmit"
    ></avue-form>
    <!-- <div class="setting-content" style="border: none;background: #fff;">
      <el-button type="primary" plain>开启筛选</el-button>
      <p class="detail-tile">点击开启设置统计范围，可通过性别、年龄等基本信息或通过选择某个阶段的某个CEF表的某道题目作为统计指标的筛选范围</p>
    </div> -->
    <div class="setting-content" style="margin-top: 0px">
      <p class="data-statistic-title">统计结果可视化展示</p>
    </div>
    <div class="chart-list-table" v-show="isChartTable">
      <div class="hint-card">
        <span>填写人数：{{ oneLndexData.length }}</span>
        <span>填写人次：{{ oneLndexData.length }}</span>
        <span style="font-weight: 550;">{{ sendCheckedTitle }}</span>
      </div>
      <div class="chart-list">
        <div ref="setChartRef1" class="chart"></div>
        <div ref="setChartRef2" class="chart"></div>
      </div>
      <avue-crud :data="oneLndexData" :option="oneLndexOption"></avue-crud>
    </div>
    <el-dialog v-model="isIndicator" title="" width="1200" body-class="QR-code-dialog-body">
      <VFormRender
        :form-json="formJson"
        :form-data="formData"
        :option-data="optionData"
        ref="vFormRef"
        @formChange="onFormDataChange"
      >
      </VFormRender>
    </el-dialog>
  </div>
</template>
<script setup>
import * as echarts from 'echarts';
import { getDetail, singleIndicatorVisualization } from '@/api/trial/trial';
import { getCrfDetail } from '@/api/crf/crf.js';
import { useStore } from 'vuex';
import VFormRender from '@/components/form-render/index.vue';
import { ref, reactive, computed, onMounted, nextTick, watch, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const crud = ref(null);
const store = useStore();
const selectTab = ref(1);
const routerQuery = ref({});
routerQuery.value = route.query;

const formJson = ref({});
const vFormRef = ref(null);
const formData = ref({});
const optionData = ref({});

let form = ref({});
let option = ref({
  submitText: '单指标统计',
  emptyBtn: false,
  menuSpan: 5,
  menuPosition: 'right',
  column: [
    {
      label: '选择分组',
      prop: 'groupId',
      type: 'select',
      dicUrl: `/api/blade-group/group/groupListOfTrial?trialId=${routerQuery.value.trialId}`,
      props: {
        label: 'name',
        value: 'id',
      },
      cascader: ['phaseId'],
      span: 5,
      rules: [
        {
          required: true,
          message: '请选择分组',
          trigger: 'blur',
        },
      ],
      filterable: true,
      overHidden: true,
    },
    {
      label: '选择阶段',
      prop: 'phaseId',
      type: 'select',
      dicUrl: `/api/blade-phase/phase/treeWithCrf?groupId={{groupId}}`,
      props: {
        label: 'title',
        value: 'id',
      },
      cascader: ['crfId'],
      span: 5,
      rules: [
        {
          required: true,
          message: '请选择阶段',
          trigger: 'blur',
        },
      ],
      filterable: true,
      overHidden: true,
    },
    {
      label: 'CRF表',
      prop: 'crfId',
      type: 'select',
      dicUrl: `/api/blade-phasecrf/phaseCrf/listOfPhase?phaseId={{phaseId}}`,
      props: {
        label: 'crfName',
        value: 'crf',
      },
      span: 5,
      rules: [
        {
          required: true,
          message: '请选择CRF表',
          trigger: 'blur',
        },
      ],
      filterable: true,
      overHidden: true,
      change: ({ value, column }) => {
        form.value.indicatorId = '';
      },
    },
    {
      label: '',
      prop: 'indicatorId',
      labelWidth: 10,
      span: 4,
      rules: [
        {
          required: true,
          message: '请选择题目',
          trigger: 'blur',
        },
      ],
      click: ({ value, column }) => {
        if (form.value.groupId != '' && form.value.phaseId != '' && form.value.crfId != '') {
          initGetCrfDetail(form.value.crfId);
        }
      },
    },
  ],
});
let isIndicator = ref(false);
const sendCheckedList = computed(() => store.getters.checkedList);
watch(
  () => sendCheckedList.value,
  (newVal, oldVal) => {
    if (newVal.length === 1) {
      form.value.indicatorId = newVal[0];
      isIndicator.value = false;
    }
  },
  { deep: true } // 深度监听对象/数组变化
);
const initGetCrfDetail = async crfId => {
  const { data: res } = await getCrfDetail(crfId);
  if (res.code == 200) {
    store.commit('SET_CHECKED_LIST', []);
    localStorage.removeItem('checkedList');
    isIndicator.value = true;
    localStorage.setItem('sendIsIndicator', true);
    formJson.value = JSON.parse(res.data.content);
    nextTick(() => {
      vFormRef.value.setFormJson(formJson.value);
    });
    setTimeout(() => {
      localStorage.removeItem('sendIsIndicator');
    }, 1000);
  }
};
let oneLndexData = ref([]);
let isChartTable = ref(false);
let sendCheckedTitle = ref('');
const handleSubmit = (form, done) => {
  singleIndicatorVisualization(
    routerQuery.value.trialId,
    form.groupId,
    form.phaseId,
    form.crfId,
    form.indicatorId
  ).then(res => {
    console.log(res);
    // ElMessage.success('操作成功');
    isChartTable.value = true;
    oneLndexData.value = res.data.data;
    sendCheckedTitle.value = localStorage.getItem('sendCheckedTitle')
    console.log(oneLndexData.value);
    nextTick(() => {
      initChart1();
      initChart2();
      window.addEventListener('resize', () => {
        chartInstance1?.resize(); // 直接调用 resize
        chartInstance2?.resize(); // 直接调用 resize
      });
    });
    done();
  });
};
let setChartRef1 = ref(null);
let chartInstance1 = null;

let setChartRef2 = ref(null);
let chartInstance2 = null;
const initChart1 = () => {
  let seriesData = [];
  oneLndexData.value.forEach(item => {
    seriesData.push({
      value:item.proportion,
      name:item.option,
      selectionNum:item.selectionNum,
    });
  });
  chartInstance1 = echarts.init(setChartRef1.value);
  let option = {
    // grid: { left: '10', right: '10', bottom: '50', top: '50', containLabel: true },
    tooltip: {
      show: true,
      formatter: function (params) {
        return params.name + '：' + params.data.selectionNum + '（' + Math.floor((Number(params.value) * 100)) + '%）';
      },
    },
    legend: {
      top: '0',
      orient: 'horizontal',
      left: 'center',
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: '50%',
        data: seriesData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  chartInstance1.setOption(option);
};
const initChart2 = () => {
  let xData = [];
  let seriesData = [];
  oneLndexData.value.forEach(item => {
    xData.push(item.option);
    seriesData.push(item.selectionNum);
  });
  chartInstance2 = echarts.init(setChartRef2.value);
  let option = {
    // grid: { left: '10', right: '10', bottom: '50', top: '50', containLabel: true },
    tooltip: {
      show: true,
      formatter: function (params) {
        return params.name + '：' + params.value;
      },
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: seriesData,
        type: 'bar',
        barWidth: 20,
      },
    ],
  };
  chartInstance2.setOption(option);
};

let oneLndexOption = ref({
  height: 'auto',
  calcHeight: 600,
  tip: false,
  border: true,
  index: false,
  selection: false,
  dialogClickModal: false,
  align: 'center',
  menu: false,
  addBtn: false,
  delBtn: false,
  viewBtn: false,
  editBtn: false,
  column: [
    {
      label: '选项',
      prop: 'option',
    },
    {
      label: '选择数',
      prop: 'selectionNum',
    },
    {
      label: '占比',
      prop: 'proportion',
    },
  ],
});
// 组件卸载时清理
onBeforeUnmount(() => {
  if (chartInstance1) {
    chartInstance1.dispose(); // 清理 chartInstance1
  }
  window.removeEventListener('resize', () => {
    chartInstance1?.resize(); // 移除事件监听
  });
  if (chartInstance2) {
    chartInstance2.dispose(); // 清理 chartInstance2
  }
  window.removeEventListener('resize', () => {
    chartInstance2?.resize(); // 移除事件监听
  });
});
</script>
<style scoped lang="scss">
.one-index-content {
  width: 100%;
  height: calc(100% - 150px);
  // overflow-y: auto;
  display: flex;
  flex-direction: column;
}
.setting-content {
  border: 1px solid #3c8dbc;
  border-left-width: 5px;
  border-radius: 3px;
  padding: 0px 10px;
  background: #f2f7fa;
  display: flex;
}
.data-statistic-title {
  line-height: 36px;
  font-size: 16px;
  align-items: center;
  justify-content: center;
  margin: 0px;
}
.detail-tile {
  margin: 0px 10px;
  color: #777;
  line-height: 36px;
  font-size: 13px;
}
.chart-list-table {
  width: 100%;
  height: auto;
  margin-top: 20px;
  flex: 1;
  // overflow-y: auto;
  margin-bottom: 10px;
  position: relative;
  ::v-deep .avue-crud__header {
    display: none;
  }
}
.hint-card {
  width: auto;
  height: 85px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  /* float: left; */
  position: absolute;
}
.chart-list {
  width: 100%;
  height: auto;
  min-height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.chart {
  width: 100%;
  height: 300px;
}
.table-list {
  width: 100%;
  height: auto;
}
</style>
